package mao.leetcode.others;

import javax.swing.*;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
 class Solution_4 {
    public static void main(String[] args) {
        Solution_4 solution = new Solution_4();
        int[] a = {1,3,2,4,3,2,1};
        ListNode head = new ListNode(a[0]);
        ListNode pre = head;
        for (int i = 1; i < a.length; i++) {
            ListNode node = new ListNode(a[i]);
            pre.next = node;
            pre=pre.next;
        }
        solution.isPalindrome(head);
    }
    public boolean isPalindrome(ListNode head) {
        if(head == null || head.next == null)
            return true;
        ListNode slow = findMid(head);
        reverse(slow);
        boolean res = compareTwoList(head,slow.next);
        reverse(slow);
        return res;
    }
    public ListNode findMid(ListNode head){
        ListNode slow = head,fast=head;
        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    public void reverse(ListNode slow){
        if(slow.next.next == null) return;
        ListNode pre = slow.next;
        ListNode cur = pre.next;
        ListNode temp = null;
        while(cur != null){
            pre.next = cur.next;
            temp = slow.next;
            slow.next = cur;
            cur.next = temp;
            cur=pre.next;
        }
    }

    public boolean compareTwoList(ListNode head1,ListNode head2){
        while(head1 != null && head2 != null){
            if(head1.val != head2.val){
                return false;
            }
            head1=head1.next;
            head2=head2.next;
        }
        return true;
    }


    private static  class ListNode {
     int val;
     ListNode next;
     ListNode(int x) { val = x; }
 }
}